using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Patient;
using B.S.NewMedical.Api.Read.DTOS.Patient;
using B.S.NewMedical.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Controllers.ContentManagement.Patient
{
    /// <summary>
    /// 患者查询控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PatientController : ControllerBase
    {
        private readonly IMediator _mediator;

        public PatientController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 根据用户ID获取患者信息
        /// </summary>
        /// <param name="accountId">用户ID</param>
        /// <returns>患者信息（包含基本信息、联系方式、病史等）</returns>
        /// <remarks>
        /// 示例：GET /api/Patient/by-account/1001
        /// 根据前端传来的用户ID，查询匹配的患者信息
        /// </remarks>
        [HttpGet]
        public async Task<ApiResult<PatientDisplayDto>> GetPatientByAccountId(int accountId)
        {
            if (accountId <= 0)
            {
                return new ApiResult<PatientDisplayDto>
                {
                    Code = ApiEnum.Fail,
                    Msg = "用户ID必须大于0"
                };
            }

            return await _mediator.Send(new GetPatientByAccountIdCommand(accountId));
        }

        /// <summary>
        /// 根据用户ID获取患者列表（获取该用户的所有患者信息）
        /// </summary>
        /// <param name="accountId">用户ID</param>
        /// <param name="includeDeleted">是否包含已删除的患者，默认false</param>
        /// <returns>患者列表（包含该用户的所有患者信息）</returns>
        /// <remarks>
        /// 示例：GET /api/Patient/list-by-account/1001?includeDeleted=false
        /// 根据用户ID查询该用户的所有患者信息，适用于一个用户可能有多个患者（如家庭成员）的场景
        /// </remarks>
        [HttpGet]
        public async Task<ApiResult<List<PatientDisplayDto>>> GetPatientsByAccountId(int accountId, [FromQuery] bool includeDeleted = false)
        {
            if (accountId <= 0)
            {
                return new ApiResult<List<PatientDisplayDto>>
                {
                    Code = ApiEnum.Fail,
                    Msg = "用户ID必须大于0",
                    Data = new List<PatientDisplayDto>()
                };
            }

            return await _mediator.Send(new GetPatientsByAccountIdCommand(accountId, includeDeleted));
        }

        /// <summary>
        /// 根据患者ID获取患者详情
        /// </summary>
        /// <param name="id">患者ID</param>
        /// <returns>患者详情（包含基本信息、联系方式、病史等）</returns>
        [HttpGet]
        public async Task<ApiResult<PatientDisplayDto>> GetPatientById(int id)
        {
            if (id <= 0)
            {
                return new ApiResult<PatientDisplayDto>
                {
                    Code = ApiEnum.Fail,
                    Msg = "患者ID必须大于0"
                };
            }

            return await _mediator.Send(new GetPatientByIdCommand(id));
        }

        /// <summary>
        /// 检查用户是否已有患者信息
        /// </summary>
        /// <param name="accountId">用户ID</param>
        /// <returns>检查结果</returns>
        /// <remarks>
        /// 用于前端判断用户是否需要完善患者信息
        /// </remarks>
        [HttpGet]
        public async Task<IActionResult> CheckPatientExists(int accountId)
        {
            if (accountId <= 0)
            {
                return BadRequest(new { Message = "用户ID必须大于0" });
            }

            var result = await _mediator.Send(new GetPatientByAccountIdCommand(accountId));
            
            return Ok(new 
            { 
                AccountId = accountId,
                HasPatientInfo = result.Code == ApiEnum.Success,
                Message = result.Code == ApiEnum.Success ? "用户已有患者信息" : "用户未录入患者信息"
            });
        }

        /// <summary>
        /// 获取患者基本信息（简化版）
        /// </summary>
        /// <param name="accountId">用户ID</param>
        /// <returns>患者基本信息（姓名、性别、年龄等）</returns>
        /// <remarks>
        /// 返回简化的患者信息，适用于卡片显示等场景
        /// </remarks>
        [HttpGet]
        public async Task<IActionResult> GetPatientBasicInfo(int accountId)
        {
            if (accountId <= 0)
            {
                return BadRequest(new { Message = "用户ID必须大于0" });
            }

            var result = await _mediator.Send(new GetPatientByAccountIdCommand(accountId));
            
            if (result.Code != ApiEnum.Success || result.Data == null)
            {
                return NotFound(new { Message = "未找到对应的患者信息" });
            }

            var patient = result.Data;
            return Ok(new 
            {
                PatientId = patient.Id,
                AccountId = patient.AccountId,
                Name = patient.Name,
                Sex = patient.Sex,
                SexText = patient.SexText,
                Age = patient.Age,
                ContactInfo = patient.ContactInfo,
                IDCardMasked = patient.IDCardMasked
            });
        }
    }
}